//
//  GMAnswerCardVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/19.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMAnswerCardVC.h"
#import "GMResultCell.h"
#import "GMSubjectsModel.h"
#import "GMAnswerItem.h"
#import "GMExamResultVC.h"
#import "GMExamHeadView.h"
@interface GMAnswerCardVC ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *titleName;
@property (weak, nonatomic) IBOutlet UILabel *score;
/**答题卡数组*/
@property (nonatomic, copy) NSArray *dataArr;
/**题目数组*/
@property (nonatomic, copy) NSArray *subDataArr;
@end

@implementation GMAnswerCardVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"答题卡";
    self.titleName.text = self.baseModel.Title;
    self.score.text = [NSString stringWithFormat:@"共%@分",self.baseModel.FullScore];
    self.dataArr = self.baseModel.AnswerCards;
    self.subDataArr = self.baseModel.Subjects;
    /**遍历数据源，组装参数*/
    for (NSInteger i =0; i<self.subDataArr.count; i++) {
         GMSubjectsModel *subModel = self.subDataArr[i];
        for (NSInteger j=0; j<self.dataArr.count; j++) {
              GMAnswerCards *model = self.dataArr[j];
            for (NSInteger m=0; m<model.Items.count; m++) {
                 GMAnswerItem *itemModel = model.Items[m];
                if ([subModel.SortNo isEqualToString:itemModel.SortNo]) {
                    itemModel.Answer = subModel.Answer;
                }
            }
        }
    }
    [self.collectionView reloadData];
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMResultCell" bundle:nil] forCellWithReuseIdentifier:@"GMResultCell"];
    [self.collectionView  registerNib:[UINib nibWithNibName:@"GMExamHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GMExamHeadView"];
}

#pragma mark - CollectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArr.count;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    GMAnswerCards * cardModel = self.dataArr[section];
    return cardModel.Items.count;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *reusableView =nil;
    if (kind == UICollectionElementKindSectionHeader){
        GMExamHeadView * headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GMExamHeadView" forIndexPath:indexPath];
        GMAnswerCards * cardModel = self.dataArr[indexPath.section];
        headView.name.text = cardModel.TypeName;
        reusableView = headView;
    }
    //如果底部视图
    if (kind ==UICollectionElementKindSectionFooter)
    {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"forIndexPath:indexPath];
        footerview.backgroundColor = [UIColor purpleColor];
        reusableView = footerview;
        
    }
    return reusableView;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMResultCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMResultCell" forIndexPath:indexPath];
    GMAnswerCards *model = self.dataArr[indexPath.section];
    GMAnswerItem *itemModel = model.Items[indexPath.row];
    itemModel.type = @"试卷答题卡";
    cell.itemModel = itemModel;
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(DEVICE_WIDTH, 44);
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((DEVICE_WIDTH-60)/5, 50);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10,10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    GMAnswerCards *model = self.dataArr[indexPath.section];
    GMAnswerItem *itemModel = model.Items[indexPath.row];
    for (NSInteger i=0; i<self.subDataArr.count; i++) {
         GMSubjectsModel *subModel = self.subDataArr[i];
        if ([subModel.SortNo isEqualToString:itemModel.SortNo]) {
            // 发送通知，定位当前题目
            [[NSNotificationCenter defaultCenter] postNotificationName:@"choseSelected" object:subModel];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
- (IBAction)sumbitBtnClick:(id)sender {
    for (GMSubjectsModel *subModel in self.subDataArr) {
        if (kIsEmptyString(subModel.Answer)) {
            //如果有题目未答，提醒
            UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"" message:@"还有题目未作答，且交卷后答题结果将不可更改，确定要交卷吗？" optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"确定" cancelTitle:@"取消" okBlock:^{
                [self handerOK];
            } cancelBlock:^{
                
            }];
            [self presentViewController:alert animated:YES completion:nil];
            /**找到如果有题目未答，直接退出循环*/
            return;
        }
        
    }
    //如果全答完
    UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"" message:@"交卷后答题结果将不可更改，确定要交卷吗" optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"确定" cancelTitle:@"取消" okBlock:^{
        [self handerOK];
    } cancelBlock:^{
        
    }];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)handerOK{
    NSMutableArray *sumbitArr = [[NSMutableArray alloc] init];
    for (NSInteger i =0; i<self.subDataArr.count; i++) {
        GMSubjectsModel *subModel = self.subDataArr[i];
        NSDictionary *sumbitDict = @{@"Id":subModel.Id,
                                     @"SortNo":subModel.SortNo,
                                     @"Answer":subModel.Answer?subModel.Answer:@"",
                                     @"StartTime":subModel.StartTime?subModel.StartTime:@"",
                                     @"UseTime":subModel.UseTime?subModel.UseTime:@""
                                     };
        [sumbitArr addObject:sumbitDict];
    }
    NSString *jsonString = sumbitArr.mj_JSONString;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"examId":self.baseModel.Id,
                          @"subjectData":jsonString
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostTestData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMExamResultVC *result = [[GMExamResultVC alloc] init];
                result.examId = self.baseModel.Id;
                [self.navigationController pushViewController:result animated:YES];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:self.view];
        }
    }];
}
@end
